package drds.global_transaction.api.message_codec.request_and_response.register_manager.resource_manager;

import drds.global_transaction.api.message_codec.request_and_response.register_manager.RegisterManagerRequestMessage;
import io.netty.buffer.ByteBuf;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.nio.ByteBuffer;

public class RegisterResourceManagerRequestMessage extends RegisterManagerRequestMessage implements Serializable
{
	private static final long serialVersionUID = 1L;
	@Setter
	@Getter
	private String resourceIds;

	public RegisterResourceManagerRequestMessage()
	{
		this(null, null);
	}

	public RegisterResourceManagerRequestMessage(String applicationId, String transactionServiceGroup)
	{
		super(applicationId, transactionServiceGroup);
	}

	@Override
	public boolean decode(ByteBuf byteBuf)
	{
		int readableBytes = byteBuf.readableBytes();
		if (readableBytes < 1)
		{
			return false;
		}

		short length = byteBuf.readShort();
		if (length > 0)
		{
			if (readableBytes < length)
			{
				return false;
			} else
			{
				readableBytes -= length;
			}
			byte[] bytes = new byte[length];
			byteBuf.readBytes(bytes);
			this.setVersion(new String(bytes, UTF8));
		}

		length = byteBuf.readShort();
		if (length > 0)
		{
			if (readableBytes < length)
			{
				return false;
			} else
			{
				readableBytes -= length;
			}
			byte[] bytes = new byte[length];
			byteBuf.readBytes(bytes);
			this.setApplicationId(new String(bytes, UTF8));
		}

		length = byteBuf.readShort();
		if (length > 0)
		{
			if (readableBytes < length)
			{
				return false;
			} else
			{
				readableBytes -= length;
			}
			byte[] bytes = new byte[length];
			byteBuf.readBytes(bytes);
			this.setTransactionServiceGroup(new String(bytes, UTF8));
		}

		length = byteBuf.readShort();
		if (length > 0)
		{
			if (readableBytes < length)
			{
				return false;
			} else
			{
				readableBytes -= length;
			}
			byte[] bytes = new byte[length];
			byteBuf.readBytes(bytes);
			this.setExtraData(new String(bytes, UTF8));
		}

		int $length = byteBuf.readInt();
		if ($length > 0)
		{
			if (readableBytes < $length)
			{
				return false;
			} else
			{
				readableBytes -= $length;
			}
			byte[] bytes = new byte[$length];
			byteBuf.readBytes(bytes);
			this.setResourceIds(new String(bytes, UTF8));
		}
		return true;
	}

	@Override
	public short getTypeCode()
	{
		return register_resource_manager_request_message;
	}

	@Override
	public ByteBuffer putBytesToByteBuffer()
	{
		ByteBuffer byteBuffer = super.putBytesToByteBuffer();
		if (this.resourceIds != null)
		{
			byte[] bytes = resourceIds.getBytes(UTF8);
			byteBuffer.putInt(bytes.length);
			if (bytes.length > 0)
			{
				byteBuffer.put(bytes);
			}
		} else
		{
			byteBuffer.putInt(0);
		}
		markAsEncode();
		return byteBuffer;

	}
}
